import React, { Component, useRef, useEffect, useState, Fragment } from 'react';
import { Drawer, Button, message, Select, Input, Space, Affix, Table, Popover, Form, Tabs, DatePicker } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import {
    CmdbContent,
    HcpTableFilterBar,
    CmdbHeader,
    TableColumsProperties,
    TempImportModal,
    HcpTableTooltip,
    Authorized,
} from '@/components';
import permission from '@/config/permission';
import cmdbres from '@/data/cmdbres';
import request, { exportFile } from '@/utils/request';
import CreateInstanceModal from './createModal';
import DeleteInstanceModal from './deleteModal';
import RelationTagModal from './relationTagModal';
import RelationBizSelect from '../ecsInstance/relationBizSelect';
import hcpUtils from '@/utils/hcpUtils';
import moment from 'moment';
import '../index.less';

const user = hcpUtils.getUser();
const BizModelCodes = ['server', 'metal_server', 'phy_server'];
const ossModelCodes = ['physics_server', 'security_device', 'network_device'];
const { RangePicker } = DatePicker;
const ResourceList = ({ history, match, location, modelInfo }) => {
    const cmModuleId = modelInfo?.cmModuleId;
    const cmModuleCode = modelInfo?.moduleCode;

    const ossModel = ossModelCodes.includes(cmModuleCode);

    const [form] = Form.useForm();
    const [properties, setProperties] = useState({});
    const [loading, setLoading] = useState(false);
    const [exportLoading, setExportLoading] = useState(false);
    const [placement, setPlacement] = useState('right');
    const [tableData, setTableData] = useState([]);
    const [row, setRow] = useState({});
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [showRelationTagModal, setShowRelationTagModal] = useState(false);
    const [showImportModal, setShowImportModal] = useState(false);
    const [tableHeaderFields, setTableHeaderFields] = useState([]);
    const [checkedFields, setCheckedFields] = useState([]);
    const [unCheckedFields, setUnCheckedFields] = useState([]);
    const [defaultCheckedFields, setDefaultCheckedFields] = useState([]);
    const [defaultUnCheckedFields, setDefaultUnCheckedFields] = useState([]);
    const [visible, setVisible] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedRows, setSelectedRows] = useState([]);
    const [query_key, setQuery_key] = useState(''); //命名采用下划线方式方便直接传值
    const [query_keyType, setQuery_keyType] = useState('');
    const [inputHolderMess, setInputHolderMess] = useState('');
    const [fieldsEnum, setFieldsEnum] = useState([]);
    const { Search } = Input;
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [activeKey, setActiveKey] = useState(0);
    const handleTabOnChange = (tab) => {
        setActiveKey(Number(tab));
    };

    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        setSelectedRowKeys([]);
        setSelectedRows([]);
        setLoading(true);
        // 云主机特殊处理，查全部按原来接口
        const flag = BizModelCodes.includes(cmModuleCode) && activeKey != 2;
        const url = flag ? cmdbres.queryBizServers : cmdbres.queryResourceList;
        try {
            const res = await request({
                ...url,
                data: {
                    cmModuleId: flag ? [cmModuleId] : cmModuleId,
                    serverType: flag ? activeKey : undefined,
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                    ...properties,
                    sort: {
                        cm_create_time: 'DESC',
                    },
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total,
                }));
                res.data.map((item, index) => {
                    item.key = index;
                    enumTranslate(item);
                });
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const getEcsTableData = async (params = { current: 1, pageSize: 10 }) => {
        setSelectedRowKeys([]);
        setSelectedRows([]);
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryBizServers,
                data: {
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                    ...properties,
                    sort: {
                        cm_create_time: 'DESC',
                    },
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total,
                }));
                res.data.map((item, index) => {
                    item.key = index;
                    enumTranslate(item);
                });
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const onFinish = () => {
        setRow({});
        let query_value = form.getFieldValue([query_key]);
        if (query_keyType == 'date') {
            setProperties({
                queryFilter: {
                    GTE: {
                        // 大于等于号（>=）
                        [query_key]: query_value?.[0] ? query_value[0].format('YYYY-MM-DD') : undefined,
                    },
                    LTE: {
                        // 小于等于号(<=)
                        [query_key]: query_value?.[1] ? query_value[1].format('YYYY-MM-DD') : undefined,
                    },
                },
            });
        } else if (query_keyType == 'datetime') {
            if (!(query_value && query_value.length)) {
                setProperties({});
                return;
            }
            setProperties({
                timeConditions: [
                    {
                        field: query_key,
                        start: query_value[0].format('YYYY-MM-DD HH:mm:ss'),
                        end: query_value[1].format('YYYY-MM-DD HH:mm:ss'),
                    },
                ],
            });
        } else if (query_keyType == 'number') {
            //
            setProperties({
                queryFilter: { EQ: { [query_key]: Number(query_value) } },
            });
        } else {
            setProperties({
                queryFilter: { LIKE: { [query_key]: query_value } },
            });
        }
    };

    useEffect(() => {
        if (properties && tableHeaderFields.length > 0) {
            getTableData();
        }
    }, [properties, tableHeaderFields, activeKey, modelInfo?.cmModuleId]);

    const enumTranslate = (data) => {
        for (let fieldKey in data) {
            if (fieldsEnum[fieldKey]) {
                let enumValue = fieldsEnum[fieldKey];
                const translateState = enumValue[data[fieldKey]];
                if (translateState) {
                    data[fieldKey] = enumValue[data[fieldKey]];
                }
            }
        }
    };

    const queryTableHeaders = async () => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: cmModuleId,
                },
            });
            setLoading(false);
            if (res && res.code == 200 && res.data && res.data.fields && res.data.fields.length) {
                let fieldData = res.data.fields.sort(function (a, b) {
                    return a.propertyIndex - b.propertyIndex;
                });
                const checkedArrs = [];
                const unCheckedArrs = [];
                let enumValues = {};
                const arr = fieldData.map((item, index) => {
                    let field = {
                        ...item,
                        key: item.propertyKey,
                        title: item.unit ? `${item.propertyName}(${item.unit})` : item.propertyName,
                        dataIndex: item.propertyKey,
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                    };

                    if (['date', 'datetime'].includes(item.propertyType)) {
                        const formString = item.propertyType == 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss';
                        field.render = (text, record) => hcpUtils.timeConversion(text, formString);
                    }

                    if (item.propertyType == 'enum' && field.woIsHidden === 0) {
                        let enumValueStr = item.propertyEnumValue.replace(/'/g, '"');
                        enumValues[field.key] = JSON.parse(enumValueStr);
                    }
                    setFieldsEnum(enumValues);

                    if (field.woIsHidden === 0) {
                        checkedArrs.push(field);
                    } else {
                        unCheckedArrs.push(field);
                    }
                    return field;
                });

                const noOperCheckedArrs = [...checkedArrs];
                const operField = {
                    title: '操作',
                    fixed: 'right',
                    width: 80,
                    woIsSystem: 1,
                    woIsHidden: 1,
                    render: (text, record, index) => {
                        return (
                            <Authorized authority={permission.instance_delete} noMatch={null}>
                                <Popover content="删除">
                                    <span
                                        className="iconfont icon-delete"
                                        onClick={() => {
                                            if (record.acceptance_status === '验收中') {
                                                message.error('该资源管理状态为验收中，不可删除！');
                                                return;
                                            }

                                            setIsBath(false);
                                            setRow(record);
                                            setShowDeleteModal(true);
                                        }}
                                    />
                                </Popover>
                            </Authorized>
                        );
                    },
                };
                checkedArrs.push(operField);
                setTableHeaderFields([
                    {
                        key: 'cm_unid',
                        title: 'ID',
                        dataIndex: 'cm_unid',
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                        render: (text, record) => (
                            <HcpTableTooltip
                                label="ID"
                                showValue={record.cm_unid}
                                copyValue={record.cm_unid}
                                onClick={() => {
                                    let mInfo = { ...modelInfo, title: undefined, icon: undefined };
                                    history.push({
                                        pathname: '/resource/catalog/detail/' + cmModuleId,
                                        state: { info: record, moduleData: mInfo, editable: !ossModel },
                                    });
                                }}
                            />
                        ),
                    },
                    ...checkedArrs,
                ]);
                setCheckedFields(noOperCheckedArrs);
                const defaultCheckedFields = JSON.parse(JSON.stringify(noOperCheckedArrs));
                setDefaultCheckedFields(defaultCheckedFields);
                setUnCheckedFields(unCheckedArrs);
                const defaultUnCheckedFields = JSON.parse(JSON.stringify(unCheckedArrs));
                setDefaultUnCheckedFields(defaultUnCheckedFields);
            } else {
                setCheckedFields([]);
                setUnCheckedFields([]);
            }
        } catch (error) {
            console.log('getTableData -> error', error);
        }
    };

    const queryUncheckedField = async (value) => {
        try {
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: cmModuleId,
                    property_name: value,
                },
            });
            if (res && res.code == 200) {
                const fieldData = res.data;
                const unCheckedArrs = [];
                fieldData.fields.map((item, index) => {
                    let field = {
                        ...item,
                        key: index,
                        title: item.propertyName,
                        dataIndex: item.propertyKey,
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                    };
                    if (field.woIsHidden === 1) {
                        unCheckedArrs.push(field);
                    }
                });
                setUnCheckedFields(unCheckedArrs);
            } else {
                setUnCheckedFields([]);
            }
        } catch (error) {
            console.log('getTableData -> error', error);
        }
    };

    useEffect(() => {
        queryTableHeaders();
    }, [modelInfo?.cmModuleId]);

    const setSelectProperty = (field) => {
        setQuery_key(field?.propertyKey);
        setQuery_keyType(field?.propertyType);
        setInputHolderMess('请输入' + (field?.propertyName || ''));
    };

    useEffect(() => {
        if (!query_key && checkedFields.length > 0) {
            setSelectProperty(checkedFields[0]);
        }
    }, [query_key]);

    useEffect(() => {
        if (checkedFields.length > 0 && checkedFields[0].propertyKey != query_key) {
            setSelectProperty(checkedFields[0]);
        }
    }, [checkedFields]);

    const resetScreen = () => {
        form.resetFields();
        if (checkedFields.length > 0) {
            const field = checkedFields[0];
            form.setFieldsValue({
                query_key: field?.propertyKey,
            });
            setSelectProperty(field);
        }
    };

    const onSelectChange = (propertyKey) => {
        const checkSelect = checkedFields.find(function (val) {
            return val.propertyKey == propertyKey;
        });
        setSelectProperty(checkSelect);
    };

    const handleTableChange = (e) => {
        getTableData(e);
    };

    const [isBath, setIsBath] = useState(false);
    const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            if (selectedRowKeys.length > 0) {
                setIsBath(true);
            } else {
                setIsBath(false);
            }
            setSelectedRowKeys(selectedRowKeys);
            setSelectedRows(selectedRows);
        },
    };

    const hasSelected = selectedRowKeys?.length > 0;
    const exportFn = async () => {
        const exportFileName = modelInfo?.moduleName + '.xlsx' || '资源.xlsx';
        setExportLoading(true);
        const res = await exportFile(
            {
                ...cmdbres.exportResourceData,
                params: {
                    cmModuleId: cmModuleId,
                    ...properties,
                    sort: {
                        create_time: 'DESC',
                    },
                },
            },
            exportFileName
        );
        setExportLoading(false);
    };

    const updateFields = () => {
        setVisible(true);
    };
    /**设置表格列组件里面的方法----------开始 */
    const onClose = () => {
        setVisible(false);
        onReset();
    };

    const onReset = () => {
        setCheckedFields(defaultCheckedFields);
        setUnCheckedFields(defaultUnCheckedFields);
    };

    const onOk = async () => {
        setLoading(true);
        let showFields = [];
        for (let item of checkedFields) {
            showFields.push(item.propertyKey);
        }
        let param = {
            namespace: 'default', //先传默认
            cm_module_id: cmModuleId,
            show_fields: showFields,
        };

        const res = await request({
            ...cmdbres.updateFieldshow,
            data: param,
        });
        setLoading(false);
        if (res && res.code == 200) {
            setVisible(false);
            message.success('修改成功！');
            queryTableHeaders();
        } else {
            if (res) message.error(res.msg);
        }
    };

    const updateUncheckedFields = (item) => {
        const newUnCheckedFields = unCheckedFields.filter(function (val) {
            return val.propertyKey != item.propertyKey;
        });
        var newCheckedFields = JSON.parse(JSON.stringify(checkedFields));
        newCheckedFields.push(item);
        setCheckedFields(newCheckedFields);
        setUnCheckedFields(newUnCheckedFields);
    };

    const updateCheckedFields = (item) => {
        const newFields = checkedFields.filter(function (val) {
            return val.propertyKey != item.propertyKey;
        });
        var newUnCheckedFields = JSON.parse(JSON.stringify(unCheckedFields));
        newUnCheckedFields.push(item);
        setCheckedFields(newFields);
        setUnCheckedFields(newUnCheckedFields);
    };
    /**设置表格列组件里面的方法----------结束 */

    return (
        <>
            <div className="resource-catalog-pane">
                {BizModelCodes.includes(cmModuleCode) && (
                    <Tabs
                        defaultActiveKey={activeKey}
                        size="large"
                        style={{ padding: '5px 0px', margin: 0 }}
                        onChange={handleTabOnChange}
                    >
                        <Tabs.TabPane tab="未分配" key={0}>
                            <></>
                        </Tabs.TabPane>
                        <Tabs.TabPane tab="已分配" key={1}>
                            <></>
                        </Tabs.TabPane>
                        <Tabs.TabPane tab="全部" key={2}>
                            <></>
                        </Tabs.TabPane>
                    </Tabs>
                )}
                <div className="session-bar">
                    <section style={{ width: '50%', float: 'left' }}>
                        <Space>
                            <Authorized authority={permission.instance_add} noMatch={null}>
                                <Button
                                    type="primary"
                                    disabled={ossModel}
                                    onClick={() => {
                                        setShowCreateModal(true);
                                    }}
                                >
                                    新建
                                </Button>
                            </Authorized>
                            <Authorized authority={permission.instance_import} noMatch={null}>
                                <Button
                                    type="primary"
                                    disabled={ossModel}
                                    onClick={() => {
                                        setShowImportModal(true);
                                    }}
                                >
                                    导入
                                </Button>
                            </Authorized>
                            <Authorized authority={permission.instance_export} noMatch={null}>
                                <Button type="primary" onClick={exportFn}>
                                    导出
                                </Button>
                            </Authorized>
                            <Authorized authority={permission.instance_delete} noMatch={null}>
                                <Button
                                    type="primary"
                                    onClick={() => {
                                        if (selectedRows.some(({ acceptance_status }) => acceptance_status === '验收中')) {
                                            message.error('存在管理状态为验收中的资源，不可批量删除！');
                                            return;
                                        }

                                        setShowDeleteModal(true);
                                    }}
                                    disabled={!hasSelected}
                                >
                                    批量删除
                                </Button>
                            </Authorized>
                            {BizModelCodes.includes(cmModuleCode) && activeKey == 0 && (
                                <RelationBizSelect
                                    assign={true}
                                    rowKeys={isBath ? selectedRowKeys : row && row.cm_unid ? [row.cm_unid] : []}
                                    getTableData={getTableData}
                                    cmModuleId={cmModuleId}
                                />
                            )}
                            {BizModelCodes.includes(cmModuleCode) && activeKey == 1 && (
                                <RelationBizSelect
                                    assign={false}
                                    rowKeys={isBath ? selectedRowKeys : row && row.cm_unid ? [row.cm_unid] : []}
                                    getTableData={getTableData}
                                    cmModuleId={cmModuleId}
                                />
                            )}
                        </Space>
                    </section>
                    <section
                        className="hcp__search__collapse hcp_search_bar"
                        style={{ display: 'inline-block', textAlign: 'right', paddingTop: '5px' }}
                    >
                        <section className="hcp__form">
                            <HcpTableFilterBar
                                form={form}
                                resetClick={resetScreen}
                                onSearch={onFinish}
                                updateFields={updateFields}
                                items={[
                                    {
                                        field: { query_key },
                                        component: (
                                            <Input.Group compact style={{ display: 'flex' }}>
                                                <Form.Item name="query_key" noStyle>
                                                    {query_key ? (
                                                        <Select
                                                            style={{ maxWidth: '110px', textAlign: 'left' }}
                                                            defaultValue={query_key}
                                                            onChange={onSelectChange}
                                                            getPopupContainer={(triggerNode) =>
                                                                triggerNode.parentElement
                                                            }
                                                        >
                                                            {tableHeaderFields && tableHeaderFields.length > 0
                                                                ? checkedFields.map((item, index) => {
                                                                      return (
                                                                          <Select.Option
                                                                              value={item.propertyKey}
                                                                              defaultValue={
                                                                                  checkedFields[0].propertyKey
                                                                              }
                                                                              key={index}
                                                                          >
                                                                              {item.propertyName}
                                                                          </Select.Option>
                                                                      );
                                                                  })
                                                                : null}
                                                        </Select>
                                                    ) : null}
                                                </Form.Item>
                                                {tableHeaderFields && tableHeaderFields.length > 0
                                                    ? tableHeaderFields.map((item, index) => {
                                                          return (
                                                              <Fragment key={index}>
                                                                  {query_key == item.propertyKey ? (
                                                                      item.propertyType == 'date' ? (
                                                                          <Form.Item
                                                                              key={item.propertyKey}
                                                                              style={{ width: '190px' }}
                                                                              name={item.propertyKey}
                                                                          >
                                                                              <RangePicker format="YYYY-MM-DD" />
                                                                          </Form.Item>
                                                                      ) : item.propertyType == 'datetime' ? (
                                                                          <Form.Item
                                                                              key={item.propertyKey}
                                                                              style={{ width: '190px' }}
                                                                              name={item.propertyKey}
                                                                          >
                                                                              <RangePicker
                                                                                  showTime
                                                                                  format="YYYY-MM-DD HH:mm:ss"
                                                                              />
                                                                          </Form.Item>
                                                                      ) : (
                                                                          <Form.Item
                                                                              key={item.propertyKey}
                                                                              style={{ width: '190px' }}
                                                                              name={item.propertyKey}
                                                                          >
                                                                              <Input
                                                                                  allowClear
                                                                                  maxLength={50}
                                                                                  placeholder={inputHolderMess}
                                                                              />
                                                                          </Form.Item>
                                                                      )
                                                                  ) : null}
                                                              </Fragment>
                                                          );
                                                      })
                                                    : null}
                                            </Input.Group>
                                        ),
                                    },
                                ]}
                            />
                        </section>
                    </section>
                </div>
                <Table
                    rowKey={(record) => record.cm_unid}
                    rowSelection={{ ...rowSelection }}
                    columns={tableHeaderFields}
                    loading={loading}
                    dataSource={tableData}
                    scroll={{ x: '100%' }}
                    pagination={{
                        showSizeChanger: true,
                        showQuickJumper: {
                            goButton: <Button style={{ margin: '0 10px' }}>确定</Button>,
                        },
                        ...pagination,
                    }}
                    onChange={handleTableChange}
                    hideSetting
                />
            </div>
            <CreateInstanceModal
                cmModuleId={cmModuleId}
                visible={showCreateModal}
                setVisible={setShowCreateModal}
                onCreateFinish={() => {
                    getTableData(pagination);
                }}
            />
            <DeleteInstanceModal
                id={cmModuleId}
                info={isBath ? selectedRowKeys : [row?.cm_unid]}
                visible={showDeleteModal}
                setVisible={setShowDeleteModal}
                onDeleteFinish={() => {
                    getTableData(pagination);
                }}
            />
            {showRelationTagModal && (
                <RelationTagModal
                    id={cmModuleId}
                    info={row}
                    visible={showRelationTagModal}
                    setVisible={setShowRelationTagModal}
                    onRelationFinish={() => {
                        getTableData(pagination);
                    }}
                />
            )}
            <TempImportModal
                title="批量导入实例"
                visible={showImportModal}
                setVisible={setShowImportModal}
                downloadApi="导入模板.xlsx" // 下载模板
                downloadParam={{ cm_module_id: cmModuleId }}
                downloadURL={'/resource/export-module-excel'} // 下载地址
                importParam={{ cm_module_id: cmModuleId }}
                importApi={cmdbres.importResource} // 导入地址
                onImportFinish={() => getTableData()}
                description={'支持格式：xlsx、xls，且不超过200M'}
            />
            {checkedFields.length > 0 ? (
                <TableColumsProperties
                    placement={placement}
                    drawerWidth={600}
                    checkedFields={checkedFields}
                    setCheckedFields={setCheckedFields}
                    unCheckedFields={unCheckedFields}
                    setUnCheckedFields={setUnCheckedFields}
                    onOk={onOk}
                    onClose={onClose}
                    onSearch={queryUncheckedField}
                    onUpdateCheckedFields={updateCheckedFields}
                    onUpdateUncheckedFields={updateUncheckedFields}
                    onReset={onReset}
                    visible={visible}
                />
            ) : null}
        </>
    );
};

export default ResourceList;
